﻿using System;
using Autodesk.AutoCAD.Runtime;
using Acap = Autodesk.AutoCAD.ApplicationServices.Application;
using JoinBox.WPF.多文档标签.View;
using JoinBox.BasalWindows;

namespace JoinBox.WPF.多文档标签
{
    public class AutoDocs : IExtensionApplication
    {
        /// <summary>
        /// 上下文管理器,跨线程处理
        /// </summary>
        public static SyncContextManager SyncManager { get; private set; } = new SyncContextManager();
        public static Anchor<DocWindow> Anchor;

        //加载dll就启动多文档标签,且可以通过命令反复调用
        public void Initialize()
        {
            try
            {
                if (Anchor != null)
                    Terminate();
                Anchor = new Anchor<DocWindow>();
            }
            catch (System.Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.Message);
            }
        }

        public void Terminate()
        {
            Anchor?.Dispose();
            Anchor = null;
        }

        //用命令来移除多文档标签
        [CommandMethod("+Duo", CommandFlags.Modal)]
        public void Cmd_AddDou()
        {
            var ed = Acap.DocumentManager.MdiActiveDocument.Editor;
            Initialize();
            ed.WriteMessage("\n添加多文档标签");
        }

        //用命令来移除多文档标签
        [CommandMethod("-Duo", CommandFlags.Modal)]
        public void Cmd_RemoveDou()
        {
            var ed = Acap.DocumentManager.MdiActiveDocument.Editor;
            Terminate();
            ed.WriteMessage("\n移除多文档标签");
        }

        public static void WriteMessage(object str)
        {
#if !WpfApp1
            AutoDocs.SyncManager.SyncContext.Post(() => {
                var ed = Acap.DocumentManager.MdiActiveDocument.Editor;
                ed.WriteMessage(Environment.NewLine + str.ToString() + Environment.NewLine);
            });
#else
            Debug.WriteLine(str);
#endif
        }

    }


}
